import React from "react";
import { FlatList, Image, StyleSheet, Text } from "react-native";
import { TouchableOpacity, View } from "react-native-ui-lib";
import { commonStyles } from "../../configs/commonStyle";
import BasePage from "../BasePage";
import ListEmpty from "../common/ListEmpty";
import { IconImage } from "../../utils";
import NavigationBar from "../common/NavigationBar";
import ViewUtils from "../../utils/ViewUtils";
import DateFilter from "../components/DateFilter";
import { inject, observer } from "mobx-react";
import moment from "moment";
import { call, setClipboardContent } from "../../utils/util";
import navigator from "../../utils/navigator";
import { NavigationEvents } from "react-navigation";

/**
 * 异常工单
 */
@inject("userStore", "appStore")
@observer
export default class WorkOrder extends BasePage {

  constructor(props) {
    super(props);
    this.pageNo = 1;
    this.pageSize = 15;
    this.totalPages = 0;
    this.isLoading = false;
    this.isFirst = true;
    this.state = {
      isRefreshing: false,
      showFoot: 0,
      showEmpty: false,
      dataList: [],
      delyStartTime: moment().format("YYYY-MM-DD"),
      delyEndTimeEnd: moment().format("YYYY-MM-DD"),
    };
  }

  loadData(showLoading = false) {
    const { delyStartTime, delyEndTimeEnd } = this.state;
    this.isLoading = true;
    let params = {
      pageNum: this.pageNo,
      // pageSize: this.pageSize,
      startTime: `${delyStartTime} 00:00:00`,
      endTime: `${delyEndTimeEnd} 23:59:59`,
      showLoading,
    };
    axios.get(api.listWorkOrderAbnormal, { params })
      .then(res => {
        this.isLoading = false;
        if (!IsNullOrEmpty(res?.result)) {
          this.setState({
            dataList: res.result,
            isRefreshing: false,
            showEmpty: IsNullOrEmpty(res.result),
          });
        } else {
          this.setState({
            showEmpty: true,
          });
        }
      })
      .catch(e => {
        logger("error", e);
        this.isLoading = false;
        this.setState({
          isRefreshing: false,
          showEmpty: true,
        });
      });
  }


  // 下拉刷新
  _renderRefresh = (isRefreshing = true) => {
    // 不处于 下拉刷新
    if (this.isLoading === false && !this.state.isRefreshing) {
      this.setState({
        isRefreshing,
      });
      this.pageNo = 1;
      this.totalPages = 0;
      this.loadData(!isRefreshing);
    }
  };

  render_item = ({ item, index }) => {
    return (
      <View>
        <View style={styles.titleWrap}>
          <TouchableOpacity activeOpacity={1} onPress={() => setClipboardContent(item?.xmbz_no)}>
            <Text style={commonStyles.text_black_14}>单号：{item?.xmbz_no}</Text>
          </TouchableOpacity>
          <Text
            style={commonStyles.text_black_14}>{moment(item?.delyTime).format("MM-DD")} {item?.delySTime}-{item?.delyETime}</Text>
        </View>
        <View style={styles.contentWrap}>
          <View style={styles.itemWrap}>
            <Text style={commonStyles.text_black_13}>状态</Text>
            <Text style={commonStyles.text_blue_13}>{item?.ordStateName}</Text>
          </View>
          <View style={styles.itemWrap}>
            <Text style={commonStyles.text_black_13}>收货人</Text>
            <Text style={commonStyles.text_black_13}>{item?.receiver_name}</Text>
          </View>
          <View style={styles.itemWrap}>
            <Text style={commonStyles.text_black_13}>分仓</Text>
            <Text style={commonStyles.text_black_13}>{item?.branch_warehouse}</Text>
          </View>
          <View style={styles.itemWrap}>
            <Text style={commonStyles.text_black_13}>联系电话</Text>
            {
              item.receiver_phone && !item.receiver_phone.includes("*") ?
                <TouchableOpacity onPress={() => call(item?.receiver_phone,item?.ordNo)}>
                  <Text style={commonStyles.text_black_13}>{item?.receiver_phone}</Text>
                </TouchableOpacity>
                : <Text style={commonStyles.text_black_13}>{item?.receiver_phone}</Text>
            }
          </View>
          <View style={styles.itemWrap}>
            <Text style={commonStyles.text_black_13}>地址</Text>
            <View marginL-10 flex right>
              <Text style={commonStyles.text_black_13}>{item?.receiver_address}</Text>
            </View>
          </View>
          <View style={styles.itemWrap}>
            <Text style={commonStyles.text_black_13}>渠道</Text>
            <Text style={commonStyles.text_black_13}>{item?.channel_name}</Text>
          </View>
          <View style={{ paddingVertical: 6 }}>
            {
              item.orderDetailList && item.orderDetailList.map(data => {
                // logger("订单号", data.isScan == 0 ? data.id : "");
                return (
                  <View row marginT-5>
                    <Image source={data.isScan == 0 ? IconImage.ic_unchecked : IconImage.ic_checked}
                           style={{ width: 17, height: 17, marginRight: 5 }} />
                    <View flex>
                      <Text
                        style={commonStyles.text_black_13}>{data?.goodsName}（{data?.goodsSpecs}）(x{data?.num}）</Text>
                    </View>
                  </View>
                );
              })
            }
          </View>
        </View>
        <View style={styles.line} />
        <View style={styles.reasonWrap}>
          <View style={styles.itemWrap2}>
            <Text style={commonStyles.text_black_13}>异常内容</Text>
            <View flex marginL-10>
              <Text style={commonStyles.text_black_13}>{item?.abnormal_content}</Text>
            </View>
          </View>
          <View style={styles.itemWrap}>
            <Text style={commonStyles.text_black_13}>处理结果</Text>
            <Text style={commonStyles.text_red_13}>{item?.processing_results}</Text>
          </View>
          {
            item?.wait_state == 2 ?
              <View right>
                <TouchableOpacity activeOpacity={1} throttleTime={1000} style={styles.btn}
                                  onPress={() => navigator.navigate("WorkOrderDetail", { item })}>
                  <Text style={commonStyles.text_black}>编辑</Text>
                </TouchableOpacity>
              </View>
              : null
          }
        </View>

      </View>
    );
  };

  render() {
    const { dataList, isRefreshing } = this.state;
    return (
      <View useSafeArea style={commonStyles.body_primary}>
        <NavigationEvents onDidFocus={() => this._renderRefresh(false)} />
        <NavigationBar
          title={"异常工单"}
          backgroundColor={"transparent"}
          leftButton={ViewUtils.getLeftButton(() => this._onBackPress())}
        />
        <View style={commonStyles.container}>
          <View row centerV>
            <DateFilter onQueryClick={(delyStartTime, delyEndTimeEnd) => this.setState({
              delyStartTime,
              delyEndTimeEnd,
            }, () => this._renderRefresh(false))} />
            <TouchableOpacity activeOpacity={1} throttleTime={1000} style={styles.btn}
                              onPress={() => this._renderRefresh(false)}>
              <Text style={commonStyles.text_black}>刷新</Text>
            </TouchableOpacity>
          </View>
          <FlatList
            data={dataList}
            onRefresh={this._renderRefresh}
            showsVerticalScrollIndicator={false}
            refreshing={isRefreshing}
            extraData={this.state}
            style={{}}
            contentContainerStyle={{ flexGrow: 1 }}
            keyExtractor={(item, index) => "menu_" + index}
            renderItem={this.render_item}
            ListEmptyComponent={() => <ListEmpty showEmpty={this.state.showEmpty} />}
          />
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  titleWrap: {
    justifyContent: "space-between",
    flexDirection: "row",
    alignItems: "center",
    borderTopLeftRadius: 4,
    borderTopRightRadius: 4,
    backgroundColor: "#F9D63B",
    marginHorizontal: 15,
    paddingHorizontal: 15,
    paddingVertical: 10,
    marginTop: 15,
  },

  contentWrap: {
    backgroundColor: "white",
    marginHorizontal: 15,
    paddingHorizontal: 15,
    paddingVertical: 10,
  },
  reasonWrap: {
    borderBottomLeftRadius: 4,
    borderBottomRightRadius: 4,
    backgroundColor: "white",
    marginHorizontal: 15,
    paddingHorizontal: 15,
    paddingVertical: 10,
  },
  itemWrap: {
    justifyContent: "space-between",
    flexDirection: "row",
    alignItems: "center",
    paddingVertical: 6,
  },
  itemWrap2: {
    justifyContent: "space-between",
    flexDirection: "row",
    paddingVertical: 6,
  },
  line: {
    height: 1,
    backgroundColor: "#EFEFEF",
    marginHorizontal: 15,
  },
  btn: {
    width: 80,
    height: 40,
    ...commonStyles.center,
    backgroundColor: "#F9D63B",
    borderRadius: 5,
  },
});
